<script setup>
  // import pdf from 'vue-pdf'
  import * as cpzzApi from '@/api/cpzzApi' 
  import $moment from "moment"
  import { v4 as uuidv4 } from 'uuid';
  import { message,loading,confirm} from 'heyui';
  import { computed, onMounted, watch } from 'vue';
  import instance from '@/utils/axios'
  import $ from 'jquery';
  import { getDocument } from 'pdfjs-dist/legacy/build/pdf';
  import 'pdfjs-dist/web/pdf_viewer.css';
  

  const pdfHeight = ref(0);

  const userId = ref("1");


  const systemTitle = ref("");
  const systemTitleIsShow = ref(false);
  const querySystemTitle = ()=>{
    cpzzApi.getSystemTitle().then(res=>{
      if(res.code == 200 && res.data){
        const {msg,isShow} = res.data
        systemTitle.value = msg;
        systemTitleIsShow.value = isShow;
      }
      pdfHeight.value =$("body").height()-(systemTitleIsShow.value?100:50);
    })
  }
  const allProductList = ref([]);
  const checkedProductItem = ref({});
  const queryTaskTree = ()=>{
    loading('加载中...');
    cpzzApi.getTaskTree().then(res=>{
      loading.close();
      const {data,code} = res;
      if(code == 200 && data.length>0){
        allProductList.value = data.filter(item=>item.children && item.children.length>0);
        checkedProductItem.value = allProductList.value[0].children[0];
        orders.value = Number(checkedProductItem.value.order);
      }else{
        message({
          type:"warning",
          text: `没有产品列表`
        });
      }
    }).catch(err=>{
      loading.close();
    })
  }
  const clickmenu = (menu)=>{
    checkedProductItem.value = menu;
  }
  watch(checkedProductItem,()=>{
    orders.value = Number(checkedProductItem.value.order);
    getRightAllProduct();
  })
  
  
  const rightActiveProduct = ref({});
  const pdfContainerRef = ref(null);
  let pdfDoc = null;
  const pdfPages = ref(0);
  const pdfScale = ref(1.5);
  watch(rightActiveProduct,async()=>{
    if(!rightActiveProduct.value.pdf_path){
      return;
    }
    const url = '/cpzzapi/proxy/product/'+rightActiveProduct.value.pdf_path; // PDF文件的URL或路径
    const loadingTask = getDocument(url);
    loadingTask.promise.then(async (pdf) => {
      pdf.loadingParams.disableAutoFetch = true;
      pdf.loadingParams.disableStream = true;
      pdfDoc = pdf; // 保存加载的pdf文件流
      pdfPages.value = pdfDoc.numPages; // 获取pdf文件的总页数
      await nextTick(() => {
        renderPage(1); // 将pdf文件内容渲染到canvas
      });
    }).catch((error) => {
      console.warn(`[upthen] pdfReader loadFile error: ${error}`);
    });
  })

  const renderPage = (num) => {
    pdfDoc.getPage(num).then((page) => {
      page.cleanup();
      if (pdfContainerRef.value) {
        pdfScale.value = pdfContainerRef.value.clientWidth / page.view[2];
      }
      const canvas = document.getElementById(`pdf-canvas-${num}`);
      if (canvas) {
        const ctx = canvas.getContext("2d");
        const dpr = window.devicePixelRatio || 1;
        const bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1;
        const ratio = dpr / bsr;
        const viewport = page.getViewport({ scale: pdfScale.value });
        canvas.width = viewport.width * ratio;
        canvas.height = viewport.height * ratio;
        canvas.style.width = viewport.width + "px";
        canvas.style.height = viewport.height + "px";
        ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
        const renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        };
        page.render(renderContext);
        if (num < pdfPages.value) {
          renderPage(num + 1);
        }
      }
    });
  };

  const downloadPdf = (product)=>{
      // PDF 文件的路径
      const pdfPath = '/cpzzapi/proxy/product/'+product.pdf_path;
      // 创建一个 <a> 元素
      const link = document.createElement('a');
      link.href = pdfPath;
      // 设置下载属性，指定下载的文件名
      link.download = product.file_name+'.pdf';
      // 模拟点击
      link.click();
  }


  const getRightAllProduct = ()=>{
    Promise.all([queryPubPDFListByTaskId(),querySavePDFListByTaskId()]).then(res=>{
        if(res && res[0].length>0){
          rightActiveProduct.value = res[0][0];
          tabActive.value = "publish"
        }else if(res && res[1].length>0){
          rightActiveProduct.value = res[1][0];
          tabActive.value = "save"
        }else{
          message({
            type:"warning",
            text: `该产品没有保存和发布的产品`
          });
          rightActiveProduct.value = {
            pdf_path:"/word/0.pdf"
          };
        }
    })
  }

  //刷新
  const refreshList = ()=>{
    clickTab({
      id:tabActive.value
    })
  }

  const clickTab = (item)=>{
    tabActive.value = item.id
    const result = (data)=>{
      if(data && data.length>0){
          rightActiveProduct.value = data[0]
        }else{
          rightActiveProduct.value = {
            pdf_path:"/word/0.pdf"
          };
        }
    }
    if(tabActive.value == "publish"){
      queryPubPDFListByTaskId().then(result)
    }else{
      querySavePDFListByTaskId().then(result)
    }
  }

  const publishlist = ref([]);
  //查询发布列表
  const queryPubPDFListByTaskId = ()=>{
    return new Promise((resolve,reject)=>{
      cpzzApi.getPubPDFListByTaskId(checkedProductItem.value.task_id).then(res=>{
        const {data,code} = res;
        if(code == 200){
          data.map(item=>{
            item.uuid = uuidv4();
          })
          publishlist.value = data;
          resolve(data);
        }else{
          publishlist.value = [];
          message({
            type:"warning",
            text: `查询发布产品失败`
          });
          reject();
        }
      })
    })
  }

  const savelist = ref([]);
  //查询保存列表 
  const querySavePDFListByTaskId = ()=>{
    return new Promise((resolve,reject)=>{
      cpzzApi.getSavePDFListByTaskId(checkedProductItem.value.task_id).then(res=>{
        const {data,code} = res;
        if(code == 200){
          data.map(item=>{
            item.uuid = uuidv4();
          })
          savelist.value = data;
          resolve(data);
        }else{
          savelist.value = [];
          message({
            type:"warning",
            text: `查询保存产品失败`
          });
          reject();
        }
      })
    })
  }

  const tabActive = ref("publish");
  const rightTab = ref([
    {id:"publish",label:"发布列表"},
    {id:"save",label:"保存列表"}
  ])

  const year = ref("2025")
  const orders = ref("1")

  //上传功能
  const uploadUrl = ref("/cpzzapi/czCpzz/cpzz/uploadWordFile");
  const uploadRef = ref()
  const beforeUploadHandle = (file)=>{
    if(file.name.indexOf(".doc") == -1){
      message({
        type:"warning",
        text: `只支持.docx或者.doc文件`
      });
      return false;
    }
  }
  const handleUploadForm = (param)=>{
      const checkItem = checkedProductItem.value;
      let formData = new FormData()
      formData.append('file', param.file);
      formData.append('modelId', checkItem.model_id);
      formData.append('orders', orders.value);
      formData.append('taskId', checkItem.task_id);
      formData.append('userId', userId.value);
      formData.append('year', year.value);
      instance.post(uploadUrl.value,formData).then((res=>{
        if (res.code == 200) {
          const data = res.data;
          if(data.absPath !=""){
            message({
              type:"success",
              text: `上传成功`
            });
            data.abspath = data.absPath;
            data.text="上传产品";
            openPageoffice(data);
          }else{
            message({
              type:"error",
              text: `上传失败`
            });
          }
        }else{
          message({
            type:"error",
            text: `上传失败`
          });
        }
        uploadRef.value.clearFiles();
      }))
  }

  //查询模板id
  const queryModelInfoByTaskId = (taskid)=>{
    return new Promise((resolve,reject)=>{
      cpzzApi.getModelInfoByTaskId(taskid).then(res=>{
        const {data,code} = res;
        if(code == 200 && data.length>0){
          resolve(data&&data.length>0?data[0].model_id:"")
        }
      })
    })
  }
  //打开word页面
  const openPageoffice = (data)=>{
    let param = `taskId=${data.taskId}&productId=${data.productId}&abspath=${encodeURIComponent(data.abspath)}&modelId=${data.modelId}&fileName=${encodeURIComponent(data.fileName)}&year=${year.value}&orders=${data.orders}&userId=${userId.value}&text=${encodeURIComponent(data.text)}`;
    POBrowser.openWindow(`pageofficemake?${param}`, "width=1720px;height=900px;fullscreen=yes");
  }

  const downloadRar = ()=>{
    const fileUrl = '/cpzzapi/proxy/product/word/file/file.rar';
    const link = document.createElement('a');
    link.href = fileUrl;
    link.download = '操作手册.rar'; // 设置下载的文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  const initmakeProPrev = ()=>{
    let text = `${checkedProductItem.value.task_name}产品最新期是第${orders.value}期,您将要制作第${Number(orders.value)+1}期,是否继续?`
    confirm({
      title: '请确认期数',
      content: text,
      onConfirm: () => {
        initmakePro();
      },
      onCancel: () => {
        message({
          type:"warning",
          text: `取消制作`
        });
      }
    });
  }
  //制作
  const initmakePro = (product)=>{
    loading('加载中...');
    if(product){
      queryModelInfoByTaskId(product?product.task_id:checkedProductItem.value.task_id).then(modeId=>{
        cpzzApi.getContinueEdit({
          fileName:product.file_name,
          modelId:modeId,
          orders:product.orders_year,
          path:product.local_path?product.local_path:product.save_path,
          taskId:product.task_id,
          userId:userId.value,
          year:product.year,
        }).then(res=>{
          loading.close();
          let {data,code} = res;
          if(code !=200 || !data.abspath){
            message({
              type:"error",
              text: `初始化产品失败`
            });
            return;
          }
          data.orders = product.orders_year;
          data.text="继续编辑";
          openPageoffice(data);
        }).catch(err=>{
          loading.close();
        })
      })
    }else{
      queryModelInfoByTaskId(product?product.task_id:checkedProductItem.value.task_id).then(modeId=>{
        cpzzApi.getinitProInfo({
          taskId:product?product.task_id:checkedProductItem.value.task_id,
          productId:product?product.product_id:checkedProductItem.value.product_id,
          modelId:modeId,
          orders:Number(orders.value)+1,
          userId:userId.value,
          year:year.value
        }).then(res=>{
          loading.close();
          let {data,code} = res;
          if(code !=200 || !data.abspath){
            message({
              type:"error",
              text: `初始化产品查询失败`
            });
            return;
          }
          data.modeId =modeId; 
          data.orders = Number(orders.value)+1;
          data.text="最新制作";
          openPageoffice(data);
        }).catch(err=>{
          loading.close();
        })
      })
    }
  }
  onMounted(()=>{
    querySystemTitle();
    queryTaskTree();
  })
</script>

<template>
<div class="cpzzMainContain">
  <div v-show="systemTitleIsShow" class="cpzzMainContaintop">{{systemTitle}}</div>
  <div class="cpzzMainContaincontent">
    <div class="cpzzMainLeft" :style="{'height':Number(Number(pdfHeight)+45)+'px'}">
      <el-menu class="el-menu-vertical-demo" :default-active="allProductList[0].children[0].product_id" v-if="allProductList&&allProductList.length>0">
        <el-sub-menu :index="item.id" v-for="item in allProductList" :key="item.id">
          <template #title>
            <el-icon><location /></el-icon>
            <span>{{item.label}}</span>
          </template>
          <el-menu-item :index="child.product_id" v-for="child in item.children" @click="clickmenu(child)">
            <template #title>
              <el-icon><location /></el-icon>
              <span>{{child.task_name}}</span>
            </template>
          </el-menu-item>
        </el-sub-menu>

      </el-menu>
    </div>
    <div class="cpzzMainCenter">
      <div class="cpzzMainCenter-top">
        <div class="cpzzMainCenter-topleft">
          <span class="icon"></span>
          <span>{{checkedProductItem.task_name}}</span>
          <el-input v-model="year" id="year"/>
          <span>年第</span> 
          <el-input v-model="orders" id="orders"/>
          <span>期</span> 
        </div>
        <div class="cpzzMainCenter-topright">
          <el-upload class="upload-demo" action="" :auto-upload="true" :limit="1" ref="uploadRef" show-file-list="false" :before-upload="beforeUploadHandle" :http-request="handleUploadForm">
            <el-button size="small"><i class="icon-upload"></i>上传</el-button>
          </el-upload>
          <el-button size="small" @click="initmakeProPrev()"><i class="icon-save"></i>制作</el-button> 
          <el-button size="small" @click="downloadRar()">操作手册</el-button> 
        </div> 
      </div>
      <div class="cpzzMainCenter-word" :style="{'height':pdfHeight+'px'}">
        <!-- <iframe v-if="rightActiveProduct && rightActiveProduct.pdf_path" :src="'/cpzzapi/proxy/product'+rightActiveProduct.pdf_path"></iframe> -->
        <div ref="pdfContainerRef" v-if="rightActiveProduct && rightActiveProduct.pdf_path">
          <canvas
            v-for="pageIndex in pdfPages"
            :id="`pdf-canvas-${pageIndex}`"
            :key="pageIndex"
          />
        </div>
        <!-- <pdf  v-if="rightActiveProduct && rightActiveProduct.pdf_path" :src="'/cpzzapi/proxy/product'+rightActiveProduct.pdf_path"></pdf> -->
        <div v-else>无文件</div>
      </div>
    </div>
    <div class="cpzzMainRight">
      <div class="cpzzMainRightTab">
        <span :class="[item.id == tabActive?'active':'']" v-for="item in rightTab" :key="item.id" @click="clickTab(item)">{{item.label}}</span>
      </div>
      <div class="cpzzMainRightcontent" v-show="tabActive=='save'"  :style="{'height':(pdfHeight-5)+'px'}">
        <div class="title">
          <span>序号</span>
          <span>名称</span>
          <span>期数</span>
          <span>保存时间</span>
          <span @click="refreshList()">操作
            <i class="h-icon-refresh"></i>
          </span>
        </div>
        <div class="content">
          <div v-for="(item,index) in savelist" :class="[rightActiveProduct.uuid == item.uuid?'active':'']" @click="rightActiveProduct = item">
            <span>{{index+1}}</span>
            <span>{{item.file_name}}</span>
            <span>{{item.orders_year}}</span>
            <span>{{item.update_time}}</span>
            <span>
              <el-button size="small" @click.prevent.stop = "downloadPdf(item)">下载</el-button>
              <el-button size="small" @click.prevent.stop = "initmakePro(item)">继续编辑</el-button>
            </span>
          </div>
        </div>
      </div>
      <div class="cpzzMainRightcontent" v-show="tabActive=='publish'"  :style="{'height':(pdfHeight-5)+'px'}">
        <div class="title">
          <span>序号</span>
          <span>名称</span>
          <span>期数</span>
          <span>发布时间</span>
          <span @click="refreshList()">操作 <i class="h-icon-refresh"></i></span>
        </div>
        <div class="content">
          <div v-for="(item,index) in publishlist" :class="[rightActiveProduct.uuid == item.uuid?'active':'']" @click="rightActiveProduct = item">
            <span>{{index+1}}</span>
            <span>{{item.file_name}}</span>
            <span>{{item.orders_year}}</span>
            <span>{{item.modify_time}}</span>
            <span>
              <el-button size="small" @click.prevent.stop = "downloadPdf(item)">下载</el-button>
              <el-button size="small" @click.prevent.stop = "initmakePro(item)">继续编辑</el-button>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</div>
</template>

<style scoped  lang="scss">
.cpzzMainContain{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 14px;
  .cpzzMainContaintop{
    width:100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    letter-spacing: 3px;
    font-size: 30px;
    color: #fff;
    font-weight: bold;
    background-image: url("@/assets/bg.png");
    background-repeat: no-repeat;
    background-position: center center;
    background-color:#3865BA;
    background-size: contain;
    //background: url("@/assets/bg.png") no-repeat center center #3865BA;
    //background-color: #3865BA;
  }
  .cpzzMainContaincontent{
    display: flex;
    gap:10px;
    flex: 1;
    background: #ededed;
    .cpzzMainLeft{
      width: 250px;
      display:flex;
      background: #fff;
      overflow-y: auto;
    }
    .cpzzMainCenter{
      flex: 1;
      display: flex;
      border: 1px solid #DCDDDD;
      flex-direction: column;
      background: #fff;
      .cpzzMainCenter-top{
        width: 100%;
        height: 45px;
        line-height: 45px;
        display: flex;
        align-items:center;
        justify-content:space-between;
        border-bottom: 5px solid #ededed;
        .cpzzMainCenter-topleft{
          flex:1;
          display: flex;
          align-items:center;
          justify-content: flex-start;
          gap: 5px;
          .icon{
            width: 30px;
            height: 45px;
            background: url("@/assets/arrow.png") no-repeat center center;
          }
        }
        .cpzzMainCenter-topright{
          justify-content: center;
          align-items: center;
          gap: 10px;
          width: 210px;
          display: flex;
        }
      }
      .cpzzMainCenter-word{
        width: 100%;
        border-bottom: 1px solid #DCDDDD;
        overflow-y: auto;
        overflow-x: hidden;
        >div{
          width: 100%;
          height: 100%;
        }
        // iframe{
        //   width: 100%;
        //   height:100%;
        // }
      }
    }
    .cpzzMainRight{
      width: 650px;
      padding: 0px 5px 5px 5px;
      background: #fff;
      display: flex;
      flex-direction: column;
      gap:5px;
      .cpzzMainRightTab{
        width: 100%;
        height: 45px;
        line-height: 45px;
        display: flex;
        align-items: center;
        font-size: 15px;
        letter-spacing: 1px;
        justify-content: space-between;
        cursor: pointer;
        border-bottom: 1px solid #DCDDDD;
        color: #797979;
        >span{
          flex: 1;
          text-align: center;
          &.active{
            color: #3865BA;
            border-bottom: 2px solid #3865BA;
          }
        }
      }
      .cpzzMainRightcontent{
        // flex: 1;
        display: flex;
        flex-direction: column;
        border: 1px solid #DCDDDD;
        cursor: pointer;
        .title{
          width: 100%;
          height: 40px;
          line-height: 40px;
          display: flex;
          background-color: #EDF0F5;
          border-btoom: 1px solid #DCDDDD;
          >span{
            text-align: center;
            font-weight: bold;
            color: #000;
          }
          >span:nth-child(1),>span:nth-child(3){
            width: 40px;
          }
          >span:nth-child(2){
           flex: 1;
          }
          >span:nth-child(4){
            width: 140px;
          }
          >span:nth-child(5){
            width: 140px;
          }
        }
        .content{
          max-height: calc(100% - 40px);
          overflow-x: hidden;
          overflow-y: auto;
          >div{
            display: flex;
            line-height: 35px;
            height: 35px;
            border-bottom: 1px solid #DCDDDD;
            &:hover,&.active{
              background-color: #E1ECFE;
            }
            >span{
              text-align: center;
            }
            >span:nth-child(1),>span:nth-child(3){
              width: 40px;
            }
            >span:nth-child(2){
            flex: 1;
            }
            >span:nth-child(4){
              width: 140px;
            }
            >span:nth-child(5){
              width: 140px;
            }
          }
        }
      }
    }
  }
}
</style>